package com.wx.qrcode.wx.util;

import java.security.MessageDigest;
import java.util.Arrays;

public class SHA1Util {

    /**
     * 用SHA1算法生成安全签名
     *
     * @param params 包含用于校验的字符串，包括： token，timestamp，nonce等
     * @return 安全签名
     */
    public static String getSHA1(String... params) {
        try {

            String[] array = params.clone();
            StringBuilder sb = new StringBuilder();
            // 字符串字典排序
            Arrays.sort(array);
            for (String anArray : array) {
                if (anArray != null) {
                    sb.append(anArray);
                }
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuilder hexstr = new StringBuilder();
            String shaHex;
            for (byte aDigest : digest) {
                shaHex = Integer.toHexString(aDigest & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            //...
            return null;
        }
    }
}